package com.spring.config;

import com.spring.pojo.User;
import com.spring.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    User user;
//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        simpleAuthorizationInfo.addStringPermission("user:add");

//        拿到当前登录的对象
//        Subject subject = SecurityUtils.getSubject();
//        User user = (User)(subject.getPrincipal());//拿到User对象
//        设置当前用户的权限，这个权限是从数据库获取的
        simpleAuthorizationInfo.addStringPermission(user.getPerms());
        return simpleAuthorizationInfo;
    }
//   认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");
//        用户名，密码  数据库中取
//        String name = "root";
//        String password = "123456";
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //        连接真实的数据库
         user = userService.queryUserByName(userToken.getUsername());
        if (user == null) {//没有这个人
            return null;
        }
//        密码认证，shiro做
//        可以加密：MD5，MD5盐值加密
        return new SimpleAuthenticationInfo("", user.getPassword(), "");
    }
}
